<template>
  <el-card>
    <el-form ref="form" :model="form" label-width="0">
      <el-form-item>
        <el-radio-group v-model="courseType" @change="handleChangeCourseType">
          <el-radio label="aipm">AI产品经理课程</el-radio>
          <el-radio label="aigc">AIGC课程</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="courseType=='aipm'">
        <el-select v-model="form.aipmClass" placeholder="请选择AIPM班级" clearable filterable style="width: 100%;">
          <el-option v-for="item in aipmClassOptions" :key="item.value" :label="item.label" :value="item">
            <span style="float: left">{{ item.label.substring(6) }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label.substr(1,4) }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="courseType=='aigc'">
        <el-select v-model="form.aigcClasses" placeholder="请选择AIGC班级" clearable filterable multiple
          style="width: 100%;">
          <el-option v-for="item in aigcClassOptions" :key="item.value" :label="item.label" :value="item.value">
            <span style="float: left">{{ item.label.substring(6) }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label.substr(1,4) }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="form.username" placeholder="请输入用户账号"></el-input>
      </el-form-item>
      <el-button type="danger" @click="createStuAccount">创建</el-button>
      <el-button type="warning" v-show="userInfo" v-clipboard:copy="userInfo" v-clipboard:success="onCopy">
        复制
      </el-button>
    </el-form>
    <el-input style="margin-top: 10px;" v-show="userInfo" rows="14" type="textarea" v-model="userInfo"></el-input>
  </el-card>
</template>
<script>
  import Vue from 'vue'
  import { ajaxGetDictItems } from '@/api/system'
  import { addUser } from '@/api/user'
  export default {
    data() {
      return {
        courseType: 'aipm',
        selectedAipmClassId: '',
        form: {
          username: null,
          aipmClass: null,
          aigcClasses: []
        },
        aipmClassOptions: [],
        aigcClassOptions: [],
        allAigcClassIds: [],
        userInfo: ''
      }
    },
    beforeDestroy() {
      document.onkeydown = null
    },
    created() {
      var that = this
      document.onkeydown = function (e) {
        var key = window.event.keyCode
        if (key == 13) {
          that.handleSubmit('loginForm')
        }
      }
      ajaxGetDictItems('open_aipm_class').then((res) => {
        if (res.success) {
          const courses = res.result.map((item) => {
            return {
              value: item.value,
              label: item.title,
            }
          })
          // aipm 课程
          this.aipmClassOptions = courses.filter((obj) => {
            return obj['label'].indexOf('aipm') > -1
          })
          // aigc 课程
          this.aigcClassOptions = courses.filter((obj) => {
            return obj['label'].indexOf('aigc') > -1
          })
          this.allAigcClassIds = this.aigcClassOptions.map(item => {
            return item.value
          })
          // 设置默认AIPM的期数
          this.aipmClassOptions.forEach(item => {
            if (item.label.indexOf('默认') > -1) {
              this.form.aipmClass = item
            }
          });
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    methods: {
      handleChangeCourseType(value) {
        if (value == 'aigc') {
          this.form.aipmClass = {}
        }
        if (value == 'aipm') {
          this.form.aigcClasses = null
        }
      },
      createStuAccount() {
        const that = this
        const courseType = this.courseType;
        let username = this.form.username;
        const aigcClasses = this.form.aigcClasses;
        const aipmClass = this.form.aipmClass;
        let selecteddeparts = [];
        // 如果不存在用户名
        if (!username || username == '')
          return this.$message.error(('请输入账号'));

        if (courseType == 'aigc' && (!aigcClasses || aigcClasses == []))
          return this.$message.error(('请选择AIGC班级'));

        if (courseType == 'aipm' && (!aipmClass || aipmClass == {} || aipmClass == '{}'))
          return this.$message.error(('请选择AIPM班级'));

        // 设置密码
        const password = Math.random().toString(36).slice(-8)
        // 设置用户名
        if (courseType == 'aipm' && /[0-9]*/.test(aipmClass.label))
          username = username + aipmClass.label.match(/[0-9][0-9]/g)[0]

        // 设置班级
        if (courseType == 'aipm') {
          selecteddeparts.push(...this.allAigcClassIds)
          // 没有完结期数 插入预习课4.0
          if (aipmClass.label.indexOf('完结') == -1)
            selecteddeparts.push('f981363644134d3d885f4b10ed6808ff')
          // 插入本期课程
          selecteddeparts.push(aipmClass.value)
        }
        else if (courseType == 'aigc') {
          selecteddeparts = aigcClasses
        }
        // 统一插入人工智能原理课
        selecteddeparts.push('e85e07733ac24f55bec2bfa963ca3218')
        // 提交请求
        const userInfo = {
          activitiSync: '1',
          username: username,
          realname: username,
          password: password,
          confirmpassword: password,
          selectedroles: '1252532277234982913',
          selecteddeparts: selecteddeparts.join(','),
          userIdentity: '1',
        }
        addUser(userInfo)
          .then((res) => {
            that.$message.success(res.message)
            that.$emit('ok')
            that.userInfo = `【AIGC产品教练课堂】学员，您好！您可直接登录教学平台学习（建议使用电脑登录）

⭐️ 课件和教学视频都在平台上面
⭐️ 课程更新后，教学平台会自动同步最新内容，刷新页面即可

🌎 地址: https://aipm.kujiajia.xyz
🌎 课程: ${courseType == 'aipm' ? aipmClass.label : 'AIGC系列课程'}
🌎 账号: ${username}
🌎 密码: ${password}

=================

我用夸克网盘分享了AI行业-课外资料包(700+份)：https://pan.quark.cn/s/f594ca940dba
提取码：uyER

${courseType == 'aipm' && '另外包含141G的AI产品经理资料库链接地址(持续更新)：https://valh4h3en3m.feishu.cn/docx/BS4Fddb9qo3eaUxorZkcyZYInWR'}`
          })
          .finally(() => {
            that.confirmLoading = false
          })

      },
      onCopy() {
        this.$message.success('复制成功')
      },
    }
  }
</script>